var com_data = {};
var com_rules = [];
var com_info={timestamp:new Date().getTime()};
var com_pagination = {pagestart: 0, pagesize: 20, count:200, pageindex: 1,sort:"machine",dir:"DESC"};
var com_rolePerLimit={checkLimit:false,NEED_ROLE:[],NEED_PER:[],ONLY_ROLE:[]};
var comJsonUtil = {data:com_data,rules:com_rules,extlimit: com_pagination,info:com_info};

// 外网接口调用_研发
var apiUrl = "http://localhost:8977";


//com_rules.push的对象
var com_rules_item = {
    field:"",
    op:"",
    data:""
};
//com_rules_item的op的类型
var com_rules_op = {
    like:"Like",
    not:"NotLike",
    ">":"GreaterThan",
    ">=":"GreaterThanOrEqualTo",
    "<":"LessThan",
    "<=":"LessThanOrEqualTo",
    "!=":"NotEqualTo",
    "in":"In",
    "notIn":"NotIn",
    "b":"Between",
    "nb":"NotBetween",
    "!null":"IsNotNull",
    "=null":"IsNull"
};

function check_User(tip) {
    if(!getLocalStorage('ZWY_accessToken')){
        if(tip){
            layer.msg("未登录!", {icon: 2,time : 2000},function () {
                x_admin_close();
                top.window.location.href = "/center/login";
            });
        }else{
            top.window.location.href = "/center/login";
        }
    }else{
        var accessToken =  getLocalStorage('ZWY_accessToken');
        if(accessToken["X-ZWY-UserType"] != 999){
            layer.msg("不是后台管理员!", {icon: 2,time : 2000},function () {
                x_admin_close();
                top.window.location.href = "/center/login";
            });
        }
    }
}

function get_axiosHttpByUser() {
    var axiosHttp = axios;
    var all_accessToken = getLocalStorage('ZWY_accessToken');
    if(all_accessToken){
        axiosHttp = axios.create({
            timeout: 6000,
            headers: {
                'Authorization': 'bearer'+all_accessToken["access_token"],
                'JSESSIONID':all_accessToken["ZWY_JSESSIONID"]
            }
        });
    }
    return axiosHttp;

}


//本地浏览器缓存验证过期
function setLocalStorage(key, value) {
    var curtime = new Date().getTime(); // 获取当前时间 ，转换成JSON字符串序列
    var valueDate = JSON.stringify({
        val: value,
        timer: curtime
    });
    try {
        localStorage.setItem(key, valueDate);
    } catch(e) {
        if(e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
            console.log("Error: 本地存储超过限制");
            localStorage.clear();
        } else {
            console.log("Error: 保存到本地存储失败");
        }
        // 兼容性写法
        if(isQuotaExceeded(e)) {
            console.log("Error: 本地存储超过限制");
            localStorage.clear();
        } else {
            console.log("Error: 保存到本地存储失败");
        }
    }
}

function isQuotaExceeded(e) {
    var quotaExceeded = false;
    if(e) {
        if(e.code) {
            switch(e.code) {
                case 22:
                    quotaExceeded = true;
                    break;
                case 1014: // Firefox
                    if(e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                        quotaExceeded = true;
                    }
                    break;
            }
        } else if(e.number === -2147024882) { // IE8
            quotaExceeded = true;
        }
    }
    return quotaExceeded;
}

function getLocalStorage(key) {
    var exp = 1000 * 60 * 60 * 10; // 10H
    if(localStorage.getItem(key)) {
        var vals = localStorage.getItem(key); // 获取本地存储的值
        var dataObj = JSON.parse(vals); // 将字符串转换成JSON对象
        // 如果(当前时间 - 存储的元素在创建时候设置的时间) > 过期时间
        var isTimed = (new Date().getTime() - dataObj.timer) > exp;
        if(isTimed) {
            console.log("存储已过期");
            localStorage.removeItem(key);
            return null;
        } else {
            var newValue = dataObj.val;
        }
        setLocalStorage(key,newValue);
        return newValue;
    } else {
        return null;
    }
}

function formatNumber(val, isDecimal) {
    if (val != null && !isNaN(val)) {
        var b = val.toString();
        var num = "";
        var num2 = "";
        var result = "";
        var decimal = false;
        if (b.indexOf(".") > 0) {
            var arr = b.split('.');
            num = arr[0].toString();
            num2 = arr[1].toString();
            decimal = true;
        } else {
            num = b;
        }

        while (num.length > 3) {
            result = ',' + num.slice(-3) + result;
            num = num.slice(0, num.length - 3);
        }
        if (num) {
            result = num + result;
        }

        if (decimal) {
            return result + "." + num2;
        }

        if (isDecimal) {
            return result + ".00";
        } else {
            return result;
        }
    }
    return "";
}

//分页算法
var calculateIndexes = function (current, length, displayLength) {
    var indexes = [];
    var start = Math.round(current - displayLength / 2);
    var end = Math.round(current + displayLength / 2);
    if (start <= 1) {
        start = 1;
        end = start + displayLength - 1;
        if (end >= length - 1) {
            end = length - 1;
        }
    }
    if (end >= length - 1) {
        end = length;
        start = end - displayLength + 1;
        if (start <= 1) {
            start = 1;
        }
    }
    for (var i = start; i <= end; i++) {
        indexes.push(i);
    }
    return indexes;
};

/**
 * 权限控制组件
 * @param objList 需要权限验证的组件列表
 * @param user 当前用户数据
 */
function permissionHandle(objList, user) {
    var permissionList = (user==null?null:user.authentication);
    for(let i=0;i<objList.length;i++) {
        var obj = $(objList[i]);
        permissionShowHandle(obj,permissionList);
    }
}

/**
 * 控制权限控制组件是否显示
 * @param obj 当前组件的权限用逗号分隔
 * @param permissionList 权限列表
 */
function permissionShowHandle(obj, permissionList) {
    let handleStr = obj.attr("permission");
    let handleList = handleStr.split(",");
    let show = false;
    // 如果当前权限为空，则直接隐藏显示
    if(permissionList.length>0) {
        // 遍历需要检查的权限
        for(let i=0;i<handleList.length;i++) {
            let handle = $.trim(handleList[i]);
            if(handle != null && handle != "") {
                // 遍历当前用户的权限
                for(let j=0;j<permissionList.length;j++) {
                    let permission = $.trim(permissionList[j].authority);
                    if(handle==permission) {
                        show = true;
                        break;
                    }
                }
            }
            if(show) {
                break;
            }
        }
    }
    // 判断组件是否能够显示
    if(!show) {
        obj.css({
            "display":"none"
        })
    }
}

//获取用户信息
function getUserInfo(userId, callback) {
    let requestData = {};
    requestData.data = {id : userId};
    axios({
        method: 'post',
        url: url+'userCenter/userInfo/get',
        data: requestData
    }).then((res) => {
        //回调函数
        callback(res);
    })
}
